/*
考虑计算cntx和k
cntx<k x需要更多位1 将x的低位0转为1
cntx==k ans=0
cntx>k x的低位1变为0
*/
#define quickread
#ifdef quickread
#include <cstdio> 
template <typename T>
inline void read(T& x)
{
    int c=getchar(), f=1; x=0;
    while(c<'0'||'9'<c) {if(c=='-') f=-1; c=getchar();}
    while('0'<=c&&c<='9') 
        x=(x<<3)+(x<<1)+c-'0', c=getchar();
    x*=f;
}
template <typename T>
inline void quickwrite(T x)
{
    if(x<0) putchar('-'), x*=-1;
    if(x>=10) quickwrite(x/10);
    putchar(x%10+'0');
}
#else 
#include <iostream>
#endif
#include <cmath>
using namespace std;
#define DEBUG
// using ll= __int128;
using ll= long long;
ll x, k, cntx;
ll ans;
ll count1(ll x)
{
    ll cnt=0;
    while(x)
    {
        cnt+=x&1;
        x>>=1;
    }
    return cnt;
}

inline ll lowbit(ll x)
{
    return x&-x;
}

void init()
{
    read(x), read(k);
    cntx=count1(x);
    ans=x;
}

void solve()
{
    init();
    if(cntx>k) //1的数量超出，需要删掉
    {
        for(ll i=cntx+1; i<=k; i++) //从最低位移除
            ans-=lowbit(ans);
    }
    else if(cntx==k) ans=0;
    else //需要多k-cntx位1
    {
        ll cnt=k-cntx;
        for(ll i=0; cnt>0; i++)
        {
            if(ans&(1<<i)) continue; //第i位本身就是1
            else ans|=(1<<i), cnt--;
            // printf("i:%lld ans:%lld\n", i, ans);
        }
    }
    quickwrite(abs(ans-x)); puts("");
}

// #undef DEBUG
signed main()
{
    #ifdef DEBUG
        freopen("../in.txt", "r", stdin);
        freopen("../out.txt", "w", stdout);
    #endif
    #ifndef quickread
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    #endif

    int T=1; scanf("%d", &T);
    while(T--) 
    {
        solve();
    }
    return 0;
}